using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SkeletonBattleState : EnemyState
{
    private Enemy_Skeleton enemy;
    private Transform playerPos;
    private int moveDir;
    public SkeletonBattleState(Enemy enemyBase, EnemyStateMachine enemyStateMachine, string animatorName, Enemy_Skeleton enemy) : base(enemyBase, enemyStateMachine, animatorName)
    {
        this.enemy = enemy;
    }

    public override void Enter()
    {
        base.Enter();
        playerPos =PlayerManager.Instance.player.transform;
        if(playerPos.GetComponent<PlayerStat>().isDead )
            enemyStateMachine.ChangeState(enemy.skeletonMoveState);
    }

    public override void Exit()
    {
        base.Exit();

    }

    public override void Update()
    {
        base.Update();
        EnemyBattle();
    }
    private void EnemyBattle()
    {
        if (enemy.PlayerDetected())
        {
            stateTimer = enemy.battleTime;
            if (enemy.attackDistance > enemy.PlayerDetected().distance)
            {
                if (CanAttack())
                    enemyStateMachine.ChangeState(enemy.skeletonAttackState);
            }
        }
        if (stateTimer < 0||Vector2.Distance(playerPos.position, enemy.transform.position)>enemy.attackOverDistance)
            enemyStateMachine.ChangeState(enemy.skeletonIdleState);

        if (playerPos.position.x > enemy.transform.position.x)
            moveDir = 1;
        else if (playerPos.position.x < enemy.transform.position.x)
            moveDir = -1;
        enemy.SetVelocity(moveDir * enemy.moveSpeed, rb.velocity.y);
    }
    private bool CanAttack()
    {
        if(Time.time>=enemy.lastAttackTime+enemy.attackCoolDown)
        {
            enemy.lastAttackTime = Time.time;
            return true;
        }
        return false;
    }
}
